package ru.ipccenter.jshell.backend.client;

import java.util.ArrayList;
import java.util.List;

import ru.ipccenter.jshell.backend.client.ImportWidget.ImportWidget;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratorPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextBox;

import net.zschech.gwt.websockets.client.ErrorHandler;
import net.zschech.gwt.websockets.client.MessageEvent;
import net.zschech.gwt.websockets.client.MessageHandler;
import net.zschech.gwt.websockets.client.OpenHandler;
import net.zschech.gwt.websockets.client.WebSocket;


/**
 * 
 */
public class JShellBackend implements EntryPoint {

  private WebSocket socket;
  private TextBox input;
  private Button send;
  
  @Override
  public void onModuleLoad() {

    HorizontalPanel hPanel = new HorizontalPanel();
    hPanel.setSpacing(2);
    
    DecoratorPanel mainDecoratorPanel = new DecoratorPanel();
    ScrollPanel scrollPanel = new ScrollPanel();
    mainDecoratorPanel.add(scrollPanel);
    scrollPanel.setSize("600px", "500px");
    
    ImportWidget importer = new ImportWidget();
    importer.uploadList();
    
    hPanel.add(mainDecoratorPanel);
    hPanel.add(importer);
    
    RootPanel.get().add(hPanel);

    
    
    input = new TextBox();
    send  = new Button("Send", new ClickHandler() {
      
      @Override
      public void onClick(ClickEvent arg0) {
        socket.send(input.getValue());
      }
    });    
    
    socket = WebSocket.create("ws://localhost:8080/JShellBackend/std-in-out-endpoint");
    
    socket.setOnOpen(new OpenHandler() {
      
      @Override
      public void onOpen(WebSocket webSocket) {}
    });
    
    socket.setOnMessage(new MessageHandler() {
      
      @Override
      public void onMessage(WebSocket webSocket, MessageEvent event) {
        send.setText(event.getData());
      }
    });
    
    socket.setOnError(new ErrorHandler() {
          @Override
          public void onError(WebSocket webSocket) {
            Window.alert("Error");
          }
    });
  }
}
